﻿#include "fakeclientpointer.h"
#include <data/replypacket.h>
#include <data/requestpacket.h>
#include <QDebug>
#include <QThread>

FakeClientPointer::FakeClientPointer()
{

}

bool FakeClientPointer::buildDataLink(const IPFiveTuple &args)
{
    Q_UNUSED(args);
    qDebug() << QObject::tr("buildLink!");
    QThread *pThd = QThread::create([&]{ doConnect(false, 1000); } );
    pThd->start();
    return true;
}

void FakeClientPointer::init(const InitArgs &args)
{
    Q_UNUSED(args);
    qDebug() << QObject::tr("init opt execute!");
    QThread *pThd = QThread::create([&]{ doConnect(true, 100); } ); // 创建线程异步执行连接的操作。
    pThd->start();
}

bool FakeClientPointer::start(const StartArgs &args)
{
    Q_UNUSED(args)
    //   （通常为客户端向服务端发送）
    // 虚拟向远端发送开始的请求 。远端收到后，正常流程应该建立连接，返回数据链路正常的状态。
    // 异常情况可能会超时。
    qDebug() << QObject::tr("Send start command to remote!");
    QThread *pThd = QThread::create([&]{ doConnect(false, 800); } );
    pThd->start();
    return true;
}

bool FakeClientPointer::stop(const StopArgs &args)
{
    //  虚拟发送停止请求
    Q_UNUSED(args)
    qDebug() << QObject::tr("Send stop command to remote!");
    return true;
}

void FakeClientPointer::request(const RequestPacket &pack)
{
    int flg = pack.flag();
//    qDebug() << QObject::tr("Send request command to remote! flag:") << flg;

    QThread *pThd = QThread::create([=]{ doReply(flg); } );
    pThd->start();
}

void FakeClientPointer::reply(const ReplyPacket &pack)
{
    qDebug() << QObject::tr("Send reply command to remote!");
    Q_UNUSED(pack)
}

void FakeClientPointer::ready()
{
    qDebug() << QObject::tr("Send ready command to remote!");
}

void FakeClientPointer::disConnect(bool bCmd)
{
    qDebug() << QObject::tr("FakeClientPointer::disconnect() !");
    onStateChange(PointerCallback::Disconnected, bCmd);
}

void FakeClientPointer::close(bool bCmd)
{
    qDebug() << QObject::tr("FakeClientPointer::close() !");
    onStateChange(PointerCallback::Disconnected, bCmd);
}

void FakeClientPointer::doConnect(bool bCmd, int waitMTime)
{
    QThread::msleep(uint(waitMTime)); // 等待一段时间后再触发消息。
    onStateChange(PointerCallback::Connected, bCmd);
    qDebug() << QObject::tr("client connect! Is cmd : ") << bCmd;
}

void FakeClientPointer::doReply(int flg)
{
    QThread::msleep(100); // 模拟延时100毫秒后收到回复。
    if(flg == 10)
    {
        QThread::msleep(2000);
    }
    ReplyPacket pack;
    pack.setFlag(flg);
    onReply(pack);
}
